package com.miaoxie.forum.module.monitor.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.baidu.ai.Base64Util;
import com.baidu.ai.GetTextByImg;
import com.baidu.aip.ocr.AipOcr;
import com.miaoxie.forum.module.auth.shared.controller.ResponseMessageController;
import com.miaoxie.forum.module.auth.shared.json.JSON;
import com.miaoxie.forum.module.auth.shared.security.SecurityNonCheckRequired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Map;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: miaoxie
 * Date: 2018-03-20
 * Time: 上午9:45
 */
@Controller
@RequestMapping("/miaoxie/baidu/ocr")
@SecurityNonCheckRequired
public class BaiduOCRController extends ResponseMessageController {
    @RequestMapping("/getBaiduOcr")
    @ResponseBody
    @JSON
    public Map<String, Object> getBaiduOcr(HttpServletRequest request, @RequestParam("file") MultipartFile file, ModelMap model) throws IOException {
        System.out.println("开始");
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();
        // String fileName = new Date().getTime()+".jpg";

//        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);

        System.out.println(path);
        String imgData = Base64Util.encode(file.getBytes());
        File targetFile = new File(path, fileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        String result = null;
        // 保存
        try {
            result =  GetTextByImg.getText(imgData);
            System.out.printf(result);
//            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        model.addAttribute("fileUrl", request.getContextPath() + "/upload/" + fileName);

        this.getMap().put("result",JSONObject.parseObject(result));
        return returnSuccess();
    }

}
